<template>
  <view class="container">
    <button type="primary" @click="chooseAndUpload">上传图片</button>

    <view v-if="fileUrl">
      <text>上传成功，文件地址：</text>
      <text selectable>{{ fileUrl }}</text>
      <image
        :src="fileUrl"
        mode="widthFix"
        style="width: 200px; margin-top: 10px"
      />
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue";

const fileUrl = ref("");

const chooseAndUpload = () => {
  uni.chooseImage({
    count: 1,
    success: (chooseResult) => {
      const tempFilePath = chooseResult.tempFilePaths[0];

      // 调用你后端的接口
      uni.uploadFile({
        url: "http://localhost:8089/wx/upload/file", // 后端接口地址
        filePath: tempFilePath,
        name: "file", // 注意要和后端 @RequestParam("file") 对应
        formData: {
          folder: "image", // 文件夹名称，可选
        },
        success: (uploadFileRes) => {
          console.log("上传成功:", uploadFileRes);
          fileUrl.value = uploadFileRes.data; // 后端返回的文件 URL
        },
        fail: (err) => {
          console.error("上传失败:", err);
          uni.showToast({ title: "上传失败", icon: "none" });
        },
      });
    },
  });
};
</script>

<style>
.container {
  padding: 20rpx;
}
</style>
